const glob = require('glob');
const fs = require('fs-extra');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const t = require('@babel/types');
const path = require('path');

const SRC_DIR = '/Users/xiaodian/Desktop/earth/src';

// 可安全平替或需注意迁移的 Antd 组件
const REPLACEABLE_COMPONENTS = [
  'Button', 'Input', 'Select', 'InputNumber', 'Checkbox', 'Radio', 'Switch',
  'DatePicker', 'TimePicker', 'Tabs', 'Dropdown', 'Tooltip',
  'Pagination', 'Spin', 'Progress', 'Badge', 'Avatar', 'Tag',
  'Card', 'Row', 'Col', 'Drawer', 'List', 'Divider', 'Alert',
  'message', 'notification', 'Modal',
  'Upload', 'Layout', 'Table', 'Popover', 'Cascader', 'Menu',
  'Breadcrumb', 'ConfigProvider', 'Skeleton', 'TreeSelect', 'Empty'
];

// Icon type 转组件名
function iconTypeToComponent(type) {
  if (!type) return null;
  return type
    .split('-')
    .map(word => word[0].toUpperCase() + word.slice(1))
    .join('') + 'Outlined';
}

glob(`${SRC_DIR}/**/*.{ts,tsx,js,jsx}`, { ignore: ['**/node_modules/**'] }, async (err, files) => {
  if (err) throw err;
  console.log('Total files found:', files.length);

  for (const file of files) {
    const code = await fs.readFile(file, 'utf-8');
    let ast;
    try {
      ast = parser.parse(code, {
        sourceType: 'module',
        plugins: [
          'typescript',
          'jsx',
          'classProperties',
          'decorators-legacy',
          'optionalChaining',
          'nullishCoalescingOperator',
          'dynamicImport',
          'exportDefaultFrom',
          'exportNamespaceFrom',
        ],
      });
    } catch (e) {
      console.warn(`⚠️ Failed to parse ${file}, skipping: ${e.message}`);
      continue;
    }

    const antdImports = new Set();
    const iconImports = new Set();
    let changed = false;

    traverse(ast, {
      ImportDeclaration(pathNode) {
        const source = pathNode.node.source.value;

        // 处理 antd import
        if (source === 'antd') {
          pathNode.node.specifiers.forEach(spec => {
            if (spec.imported && REPLACEABLE_COMPONENTS.includes(spec.imported.name)) {
              antdImports.add(spec.imported.name);
              changed = true;
            }
            if (spec.imported && spec.imported.name === 'Icon') {
              changed = true;
            }
          });

          pathNode.node.specifiers = pathNode.node.specifiers.filter(s => {
            const name = s.imported ? s.imported.name : null;
            return !(REPLACEABLE_COMPONENTS.includes(name) || name === 'Icon');
          });

          if (pathNode.node.specifiers.length === 0) pathNode.remove();
        }

        // 合并 @ant-design/icons import
        if (source === '@ant-design/icons') {
          pathNode.node.specifiers.forEach(spec => {
            if (spec.imported) iconImports.add(spec.imported.name);
          });
          pathNode.remove();
          changed = true;
        }
      },

      JSXElement(pathNode) {
        const opening = pathNode.node.openingElement;
        if (!opening || !opening.name || opening.name.name !== 'Icon') return;

        const typeAttr = opening.attributes.find(a => a.name && a.name.name === 'type');
        if (!typeAttr || !typeAttr.value) return;

        const createJSX = (iconName) => t.jSXElement(
          t.jSXOpeningElement(t.jSXIdentifier(iconName), [], true),
          null,
          [],
          true
        );

        const replaceWithExpr = (expr) => {
          // 字符串
          if (expr.type === 'StringLiteral') {
            const iconName = iconTypeToComponent(expr.value);
            if (iconName) {
              iconImports.add(iconName);
              pathNode.replaceWith(createJSX(iconName));
              changed = true;
            }
          }
          // 三元表达式
          else if (expr.type === 'ConditionalExpression') {
            const consIcon = iconTypeToComponent(expr.consequent.value);
            const altIcon = iconTypeToComponent(expr.alternate.value);
            if (consIcon && altIcon) {
              iconImports.add(consIcon);
              iconImports.add(altIcon);
              pathNode.replaceWith(
                t.jSXExpressionContainer(
                  t.conditionalExpression(
                    expr.test,
                    createJSX(consIcon),
                    createJSX(altIcon)
                  )
                )
              );
              changed = true;
            }
          }
        };

        if (typeAttr.value.type === 'StringLiteral') {
          replaceWithExpr(typeAttr.value);
        } else if (typeAttr.value.type === 'JSXExpressionContainer') {
          replaceWithExpr(typeAttr.value.expression);
        }
      }
    });

    // 生成 import，合并同一库的组件
    const importNodes = [];
    if (antdImports.size > 0) {
      const specifiers = [...antdImports].sort().map(name => t.importSpecifier(t.identifier(name), t.identifier(name)));
      importNodes.push(t.importDeclaration(specifiers, t.stringLiteral('antd-v5')));
    }
    if (iconImports.size > 0) {
      const specifiers = [...iconImports].sort().map(name => t.importSpecifier(t.identifier(name), t.identifier(name)));
      importNodes.push(t.importDeclaration(specifiers, t.stringLiteral('@ant-design/icons')));
    }

    if (importNodes.length > 0) {
      ast.program.body = [...importNodes, ...ast.program.body];
    }

    if (changed) {
      const output = generate(ast, { quotes: 'single', retainLines: false, concise: false }).code;
      await fs.writeFile(file, output, 'utf-8');
      console.log(`✅ Updated components/icons in: ${file}`);
    }
  }

  console.log('🎉 Migration finished! Components and icons migrated.');
});

 // 将 "menu-fold" -> "MenuFoldOutlined"
 // import * as Icons from '@ant-design/icons';
 // const iconName = icon.split('-').map(word => word[0].toUpperCase() + word.slice(1)).join('') + 'Outlined';
 // const IconComponent = Icons[iconName];